import { BizKfExtraProColumnType } from '@/components';
import * as API from '@/services';
import { Divider, message, Space, Typography } from 'antd';
import { getBooleanToProTableValueEnum, KfModal, KfPagingTablePage, KfPagingTablePagePropsAction, useBackendEnum, useKeepAliveContext } from 'kf-web-library';
import React, { useRef } from 'react';
import { useLocation, useAccess } from 'umi';
import { FilePdfOutlined, UserOutlined } from '@ant-design/icons';
import QuickForm from './components/QuickForm';
import './index.less';
import dayjs from 'dayjs';
import SpecialTopicQuickForm from '@/pages/biz/Article/components/SpecialTopicQuickForm';
import { createChiefSelected, deleteChiefSelectedByArticleId, modifyArticleSpecialTopicId } from '@/services';
import ChiefSelectedQuickForm from '@/pages/biz/Article/components/ChiefSelectedQuickForm';
import { useParams, useRequest } from '@@/exports';
import queryString from 'query-string';
import { getAuthToken } from '@/utils/auth';
import { downloadArticlePdf } from '@/utils/download';

type Entity = API.Article;
type EntityPageQueryParams = API.RolePageQueryParams;
const entityTypeName = '文章';
const EntityQuickForm = QuickForm;

interface EntityTableListProps {}

/**
 * 文章 列表页面
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const location = useLocation();
  const { specialTopicId } = useParams();
  const access = useAccess();
  const { enumDict, enumTypeDict, getBackendEnum } = useBackendEnum();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();
  const { updateTab } = useKeepAliveContext() || {};

  const specialTopicDetail = useRequest(() => API.queryJournalSpecialTopic(specialTopicId!), {
    refreshDeps: [specialTopicId],
    ready: !!specialTopicId,
    onSuccess: (res) => {
      updateTab?.(location.pathname, {
        name: `特殊类型"${res?.name}"的关联文章`,
      });
    },
  });

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      pagingQuery={(p) =>
        API.queryArticles({
          specialTopicId,
          ...p,
        })
      }
      opActionsDef={{
        single: {
          deleteOne: (record) => {
            KfModal.deleteConfirm(record.articleTitleCn as string, () => {
              API.deleteArticle(record.id!).then((res) => {
                if (res.flag) {
                  message.info('删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
          deleteChiefSelectedOne: (record) => {
            KfModal.confirm('取消主编精选', record.articleTitleCn as string, () => {
              API.deleteChiefSelectedByArticleId(record.id!).then((res) => {
                if (res.flag) {
                  message.info('取消主编精选成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
          deleteSpecialTopicOne: (record) => {
            KfModal.confirm('取消特殊类型文章', record.articleTitleCn as string, () => {
              API.modifyArticleSpecialTopicId({ articleId: record.id!, specialTopicId: null }).then((res) => {
                if (res.flag) {
                  message.info('取消特殊类型文章成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
        multi: {
          deleteMultiple: (records) => {
            KfModal.batchActionConfirm('删除', records.length, () => {
              API.deleteArticles(records.map((r) => r.id!)).then((res) => {
                if (res.flag) {
                  message.info('批量删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
      }}
      opFloatingsDef={{
        noargs: {
          createModal: () => ({
            title: `新建`,
            content: <EntityQuickForm formType={'create'} />,
          }),
        },
        single: {
          addSpecialTopicModal: (record) => ({
            title: `标为特殊类型文章`,
            content: <SpecialTopicQuickForm formType={'modify'} bizId={record.id} />,
          }),
          addChiefSelectedModal: (record) => ({
            title: `标为编辑精选文章`,
            content: <ChiefSelectedQuickForm formType={'create'} bizId={record.id} />,
          }),
          modifyModal: (record) => ({
            title: `编辑`,
            width: 800,
            content: <EntityQuickForm formType={'modify'} bizId={record.id} />,
          }),
          viewModal: (record) => ({
            fltType: 'modal',
            title: `查看`,
            width: 800,
            content: <EntityQuickForm formType={'view'} bizId={record.id} />,
          }),
        },
      }}
      proTable={{
        tableBarActions: (action, rows) => {
          return [];
        },
        search: {
          optionRender: (searchConfig, formProps, dom) => [...dom],
        },
      }}
      columns={[
        {
          title: '关键字',
          dataIndex: 'searchText',
          sorter: false,
          hideInTable: true,
          hideInForm: true,
          fieldProps: {
            placeholder: '文章标题',
          },
        },
        {
          title: '序号',
          width: 50,
          key: '_seq_index_',
          align: 'center',
          hideInSearch: true,
          valueType: 'index',
          render: (dom, record, index) => {
            const pageInfo = actionRef.current?.queryParams();
            return ((pageInfo?.current || 1) - 1) * (pageInfo?.pageSize || 0) + (index + 1);
          },
        },

        {
          title: 'DOI',
          width: 260,
          dataIndex: nameof<Entity>((x) => x.articleDoi),
          sorter: false,
          hideInSearch: true,
        },
        {
          title: '文章标题',
          dataIndex: nameof<Entity>((x) => x.articleTitleCn),
          sorter: false,
          hideInSearch: true,
          render: (dom, record) => {
            return <div dangerouslySetInnerHTML={{ __html: record.articleTitleCn || '' }} />;
          },
        },
        {
          title: '所属期刊',
          dataIndex: 'journalId',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          valueType: 'hxJournalPicker',
        },
        {
          title: '所属刊期',
          dataIndex: 'periodId',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          valueType: 'hxJournalPeriodPicker',
        },
        {
          title: '所属栏目',
          dataIndex: 'columnId',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          valueType: 'hxJournalColumnPicker',
        },
        {
          title: (
            <div>
              <div>所属期刊</div>
              <div>刊期/起止页/栏目</div>
            </div>
          ),
          width: 280,
          ellipsis: true,
          dataIndex: nameof.split<Entity>((x) => x.journal.journalNameCn),
          hideInSearch: true,
          render: (dom, record) => {
            return (
              <div>
                <div>{record.journal.journalNameCn}</div>
                <div>
                  <Space size={0} split={'，'}>
                    <span>{record.period?.periodName}</span>
                    <span>
                      {record.articleStartpage}-{record.articleEndpage}页
                    </span>
                  </Space>
                </div>
                <div>{record.column?.name}</div>
              </div>
            );
          },
        },
        {
          title: '是否主编精选',
          dataIndex: 'chiefSelected',
          width: 100,
          sorter: false,
          hideInSearch: false,
          hideInTable: false,
          valueEnum: getBooleanToProTableValueEnum('是', '否'),
        },
        {
          title: '特殊类型',
          width: 100,
          dataIndex: nameof.split<Entity>((x) => x.specialTopic.name),
          sorter: false,
          hideInSearch: true,
        },
        {
          title: '是否特殊类型',
          dataIndex: 'withinSpecialTopic',
          sorter: false,
          hideInSearch: !!specialTopicId,
          hideInTable: true,
          valueEnum: getBooleanToProTableValueEnum('是', '否'),
        },
        {
          title: '首发日期',
          width: 100,
          ellipsis: true,
          dataIndex: nameof.split<Entity>((x) => x.articlePublishedDate),
          hideInSearch: false,
          render: (text, record) => {
            return record.articlePublishedDate ? dayjs(record.articlePublishedDate).format('YYYY-MM-DD') : null;
          },
          valueType: 'dateRange',
        },
        {
          title: '作者',
          width: 240,
          ellipsis: true,
          dataIndex: nameof.split<Entity>((x) => x.articleAuthorCn),
          hideInSearch: true,
        },
        {
          title: '文章PDF',
          width: 80,
          ellipsis: true,
          align: "center",
          dataIndex: nameof.split<Entity>((x) => x.articlePdfExist),
          hideInSearch: false,
          render: (text, record) => {
            if (!record.articlePdfExist) {
              return null;
            }
            return (
              <a onClick={() => downloadArticlePdf(record)}>
                <FilePdfOutlined />
              </a>
            );
          },
          valueEnum: getBooleanToProTableValueEnum('有', '无'),
        },
        {
          title: '操作',
          fixed: 'right',
          width: 230,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
            <Space size={0} split={<Divider type="vertical" />}>
              {record.chiefSelected ? (
                <a onClick={() => actionRef.current?.executeAction.single?.deleteChiefSelectedOne(record)}>
                  <Typography.Text type="danger">取消精选</Typography.Text>
                </a>
              ) : (
                <a onClick={() => actionRef.current?.openFloating.single?.addChiefSelectedModal(record, 'modal')}>
                  <Typography.Text type="success">标为精选</Typography.Text>
                </a>
              )}
              {record.specialTopic ? (
                <a onClick={() => actionRef.current?.executeAction.single?.deleteSpecialTopicOne(record)}>
                  <Typography.Text type="danger">取消特殊</Typography.Text>
                </a>
              ) : (
                <a onClick={() => actionRef.current?.openFloating.single?.addSpecialTopicModal(record, 'modal')}>
                  <Typography.Text type="success">标为特殊</Typography.Text>
                </a>
              )}
              <a
                onClick={() => {
                  actionRef.current?.openFloating.single?.modifyModal(record, 'modal');
                }}
              >
                编辑
              </a>
              {/*<a onClick={() => {
                actionRef.current?.executeAction.single?.deleteOne(record)
              }}>
                <Typography.Text type="danger">删除</Typography.Text>
              </a>*/}
            </Space>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
